<?php
/**
 * Generate a {@link https://www.google.com/webmasters/tools/docs/en/protocol.html Google Sitemap}
 * to optimize indexing of the wiki.
 *
 * @package     Handlers
 * @subpackage  XML
 * @version     $Id$
 * @license     http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @filesource
 *
 * @author      {@link http://wikkawiki.org/BarkerJr BarkerJr} initial code
 * @author      {@link http://wikkawiki.org/DarTar Dario Taraborelli}
 * @author      {@link http://klenwell.com/is Tom at klenwell@gmail.com}
 *
 * @uses        Config::$base_url
 * @uses        Config::$table_prefix
 * @todo        - Calculate optimal changefreq for each page depending on actual revision history
 */

require_once 'libs/action.class.php';

class SitemapHandler extends WikkaAction {

    /**
     * How frequently a page is likely to change. This value provides general
     * information to search engines and may not correlate exactly to how often
     * they crawl the page. Valid values are: always, hourly, daily, weekly,
     * monthly, yearly, never
     */
    var $default_frequency = 'monthly';
    var $FrequencyList = array(
        'HomePage'      => 'weekly'
    );

    /**
     * The priority of this URL relative to other URLs on your site. Valid
     * values range from 0.0 to 1.0. This value has no effect on your pages
     * compared to pages on other sites, and only lets the search engines know
     * which of your pages you deem most important so they can order the crawl
     * of your pages in the way you would most like. The default priority of a
     * page is 0.5.
     */
    var $default_priority = 0.5;
    var $PriorityList = array(
        'HomePage'      => 1.0
    );

    var $header = 'Content-Type: text/xml; charset=utf-8';
    var $atom_date_f = 'c';
    var $list_limit = 200;

    function main() {
        header($this->header);
        print $this->build_xml();
    }

    function build_xml() {
        $xmldoc_f = <<<XMLDOC
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
    http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
%s
</urlset>
XMLDOC;

        $xmlurl_f = <<<XMLDOC
    <url>
        <loc>%s</loc>
        <priority>%s</priority>
        <changefreq>%s</changefreq>
        <lastmod>%s</lastmod>
    </url>
XMLDOC;

        $sql_f = <<<SQLDOC
SELECT SQL_NO_CACHE id, tag,
    MAX(time) AS latest,
    MIN(time) AS first,
    DATEDIFF(MAX(time), MIN(time)) AS daydiff,
    COUNT(DISTINCT(CAST(time AS CHAR(10)))) AS revisions
FROM %s
GROUP BY tag
ORDER BY revisions DESC
LIMIT %s;
SQLDOC;

        $pages_table = $this->Wikka->GetConfigValue('table_prefix') . 'pages';
        $Rows = $this->Wikka->LoadAll(sprintf($sql_f, $pages_table, $this->list_limit));

        $UrlList = array();
        $base_url = $this->get_config('base_url');
        foreach ( $Rows as $Row ) {
            $loc = sprintf('%s%s', $base_url, $Row['tag']);
            $priority = ( isset($this->PriorityList[$Row['tag']]) )
                ? $this->PriorityList[$Row['tag']]
                : $this->default_priority;
            $changefreq = ( isset($this->FrequencyList[$Row['tag']]) )
                ? $this->FrequencyList[$Row['tag']]
                : $this->default_frequency;
            $lastmod = date($this->atom_date_f, strtotime($Row['latest']));
            $UrlList[] = sprintf($xmlurl_f, $loc, $priority, $changefreq, $lastmod);
        }

        return sprintf($xmldoc_f, implode("\n", $UrlList));
    }
}

# Main Routine
try {
    $Handler = new SitemapHandler($this);
    $Handler->main();
}
catch(Exception $e) {
    print $e->getMessage();
}

?>
